package com.aaa.inside.controller;


import com.aaa.entity.base.Commodity;
import com.aaa.entity.base.Warehouse;

import com.aaa.entity.inside.Allocation;
import com.aaa.entity.inside.AllocationDetail;
import com.aaa.entity.inside.Puton;
import com.aaa.entity.stock.Stock;
import com.aaa.entity.system.User;
import com.aaa.inside.feign.BaseFeign;
import com.aaa.inside.feign.StockFeign;
import com.aaa.inside.feign.SystemFeign;

import com.aaa.inside.service.AllocationDetailService;
import com.aaa.inside.service.AllocationService;
import com.aaa.inside.util.JwtUtils;
import com.aaa.inside.vo.AllDetail;
import com.aaa.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author aaa
 * @since 2020-12-07
 */
@RestController
@RequestMapping("/inside/allocation")
public class AllocationController{
    @Autowired
    private BaseFeign baseFeign;
    @Autowired
    private AllocationService allocationService;
    @Autowired
    private SystemFeign systemFeign;
    @Autowired
    private AllocationDetailService detailService;
    @Autowired
    private StockFeign stockFeign;
    /*查询所有仓库*/
    @ApiOperation("查询所有仓库")
    @PostMapping("searchWare")
    public R searchWare(){
        List<Warehouse> warehouses = baseFeign.searchWare();
        return R.ok().data("warehouses",warehouses);
    }
    /*调拨*/
    @ApiOperation("调拨")
    @PostMapping("allocation")
    public R allocation(@RequestBody Allocation allocation, HttpServletRequest request  ){
        Warehouse awarehouse = baseFeign.selectWareById(allocation.getAwarehouseid());
        Warehouse bwarehouse = baseFeign.selectWareById(allocation.getBwarehouseid());
        Allocation allocation1=new Allocation();
        allocation1.setAllocationno(allocation.getAllocationno());
        allocation1.setBwarehouseid(allocation.getBwarehouseid());
        allocation1.setBwarehousename(bwarehouse.getName());
        allocation1.setAwarehouseid(allocation.getAwarehouseid());
        allocation1.setAwarehousename(awarehouse.getName());
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        allocation1.setCreateid(userid);
        allocation1.setCreator(user.getName());
        Date now=new Date();
        allocation1.setCreatetime(now);
        boolean save = allocationService.save(allocation1);
        if (save){
            return R.ok().message("调拨成功").data("allocationno",allocation.getAllocationno());
        }
        else {
            return R.error().message("服务器异常");
        }
    }
    /*查询非默认仓库的货位*/
    @ApiOperation("查询非默认仓库的货位")
    @PostMapping("selectIMoLo")
    public List<Map> selectIMoLo(){
        return baseFeign.selectIMoLo();
    }
    /*查询所有非默认仓库的商品*/
    @ApiOperation("查询所有非默认仓库库存")
    @PostMapping("selectStoCom")
    public List<Stock> selectStoCom(){
        return stockFeign.selectStoCom();
    }
    /*调拨添加明细按钮*/
    @ApiOperation("调拨添加明细按钮")
    @PostMapping("addAllDetail")
    public R addAllDetail(@RequestBody AllDetail allDetail,HttpServletRequest request){
        if(allDetail.getQty()==0){
            return R.error().message("数量不能为0，请重新输入");
        }
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        Stock stock = stockFeign.selectStockByComBarOriLo(allDetail.getCommoditybar(), allDetail.getLocatorcode(), 42L);
        if (stock.getUqty()>=allDetail.getQty()){
            AllocationDetail detail1=detailService.selectDeByaNoLBar(allDetail.getAllocationno(),allDetail.getLocatorcode(),allDetail.getCommoditybar());
            if (detail1!=null){
                if (detail1.getQty()+allDetail.getQty()<=stock.getUqty()){
                    detail1.setQty(detail1.getQty()+allDetail.getQty());
                    boolean b = detailService.updateById(detail1);
                    if (b){
                        return R.ok().message("添加明细成功");
                    }else {
                        return R.error().message("添加失败");
                    }
                }else {
                    return R.error().message("该库位商品库存不足请核实！");
                }

            }else {
                AllocationDetail detail=new AllocationDetail();
                QueryWrapper<Allocation> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("allocationno",allDetail.getAllocationno());
                Allocation allocation = allocationService.getOne(queryWrapper);
                Commodity commodity = baseFeign.selectComIdNamByWareIdCbar(allDetail.getCommoditybar(), 42L);
                Date now=new Date();
                detail.setPid(allocation.getId());
                detail.setLocatorcode(allDetail.getLocatorcode());
                detail.setCommodityid(commodity.getId());
                detail.setCommodityname(commodity.getName());
                detail.setCommoditybar(commodity.getBar());
                detail.setQty(allDetail.getQty());
                detail.setCreator(user.getName());
                detail.setCreatetime(now);
                boolean a = detailService.save(detail);
                if (a){
                    return R.ok().message("添加明细成功");
                }else {
                    return R.error().message("添加失败");
                }
            }

        }else {
            return R.error().message("该库位商品库存不足请核实！");
        }
    }
    /*结束调拨录入明细*/
    @ApiOperation("结束调拨录入明细")
    @PostMapping("endDetail/{allocationno}")
    public R endDetail(@PathVariable String allocationno){
        QueryWrapper<Allocation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("allocationno",allocationno);
        Allocation allocation = allocationService.getOne(queryWrapper);

        QueryWrapper<AllocationDetail> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("pid",allocation.getId());
        List<AllocationDetail> details=detailService.list(queryWrapper1);
        if(details.size()==0){
            return R.error().message("明细不能为空，请先录入明细");
        }else {
            allocation.setState("1");
            boolean b = allocationService.updateById(allocation);
            if (b){
                return R.ok().message("调拨结束成功");
            }
            return R.error().message("服务器异常");
        }

    }
    /*删除调拨信息*/
    @ApiOperation("删除调拨信息")
    @PostMapping("deleteAllo/{allocationno}")
    public R deleteAllo(@PathVariable String allocationno){
        QueryWrapper<Allocation> query1=new QueryWrapper<>();
        query1.eq("allocationno",allocationno);
        Allocation allocation = allocationService.getOne(query1);
        QueryWrapper<AllocationDetail> query2=new QueryWrapper<>();
        query2.eq("pid",allocation.getId());
        List<AllocationDetail> details=detailService.list(query2);
        if (details.size()==0){
            QueryWrapper<Allocation> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("allocationno",allocationno);
            boolean b = allocationService.remove(queryWrapper);
            if (b){
                return R.ok().message("删除成功");
            }else {
                return R.error().message("删除失败");
            }
        }
        boolean a =detailService.deleteDetailByNo(allocationno);
        if (a){
                QueryWrapper<Allocation> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("allocationno",allocationno);
                boolean b = allocationService.remove(queryWrapper);
            if (b){
                return R.ok().message("删除成功");
            }else {
                return R.error().message("删除失败");
            }
        }else {
            return R.error().message("删除失败");
        }
    }
    /*显示所有明细*/
    @ApiOperation("显示所有明细")
    @PostMapping("selectAllDetail/{allocationno}")
    public List<AllocationDetail> selectAllDetail(@PathVariable String allocationno){
        return detailService.selectAllDetail(allocationno);
    }
    /*查看所有调拨管理*/
    @ApiOperation("查看所有调拨管理")
    @PostMapping("searchAllo/{page}/{limit}")
    public R searchAllo(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody Allocation allocation){
        return allocationService.searchAllo(page,limit,allocation);
    }
    /*调拨审核操作*/
    @ApiOperation("调拨审核操作")
    @PostMapping("alloCheck")
    public R alloCheck(@RequestBody Allocation allocation,HttpServletRequest request){
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        if (allocation.getState().equals("0")){
            return R.error().message("此订单尚未结束录入明细，请先结束");
        }
        if (allocation.getState().equals("2")){
            return R.error().message("该订单已审核请勿重复审核");
        }else {
            QueryWrapper<AllocationDetail> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("pid",allocation.getId());
            List<AllocationDetail> details=detailService.list(queryWrapper);
            int a=0;
            for (AllocationDetail detail:details){
                Stock stock = stockFeign.selectStockByComBarOriLo(detail.getCommoditybar(), detail.getLocatorcode(), 42L);
                if (detail.getQty()>stock.getUqty()){
                    a++;
                    break;
                }
            }
            if (a==0){
                for (AllocationDetail detail:details){
                    Stock stock = stockFeign.selectStockByComBarOriLo(detail.getCommoditybar(), detail.getLocatorcode(), 42L);
                    stock.setLqty(detail.getQty()+stock.getLqty());
                    stock.setUqty(stock.getUqty()-detail.getQty());
                    stockFeign.updateById(stock);
                }
                allocation.setState("2");
                Date now=new Date();
                allocation.setAudittime(now);
                allocation.setAuditor(user.getName());
                boolean b = allocationService.updateById(allocation);
                if (b){
                    return R.ok().message("审核成功");
                }else {
                    return R.error().message("系统错误");
                }

            }else {
                return R.error().message("库存不足，请安排仓库人员进货");
            }

        }
    }
    /*调拨撤销审核操作*/
    @ApiOperation("调拨撤销审核操作")
    @PostMapping("cancelCheck")
    public R cancelCheck(@RequestBody Allocation allocation) {
        if (!allocation.getState().equals("2")){
            return R.error().message("此订单尚未审核，请核实！");
        }
        QueryWrapper<AllocationDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", allocation.getId());
        List<AllocationDetail> details = detailService.list(queryWrapper);
        for (AllocationDetail detail : details) {
            Stock stock = stockFeign.selectStockByComBarOriLo(detail.getCommoditybar(), detail.getLocatorcode(), 42L);
            stock.setLqty(stock.getLqty() - detail.getQty());
            stock.setUqty(stock.getUqty() + detail.getQty());
            stockFeign.updateById(stock);
        }
        allocation.setState("1");
        boolean b = allocationService.updateById(allocation);
        if (b) {
            return R.ok().message("撤销审核成功");
        }else {
            return R.error().message("撤销审核失败");
        }

    }

}

